package belf.migrate.plugin.postgresql;

import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PostgreSqlDDLBuilder {

    public static Map<String, String> getSequenceDDL(Connection connection, String schema, List<String> sequenceNames) throws SQLException {
        // 存储序列名称和对应的 DDL 语句
        Map<String, String> sequenceDDLMap = new HashMap<>();

        // SQL 查询，获取序列信息
        String sql = "SELECT n.nspname AS schema_name, " +
                "       c.relname AS sequence_name, " +
                "       s.start_value, " +
                "       s.increment_by, " +
                "       s.min_value, " +
                "       s.max_value, " +
                "       s.cache_size, " +
                "       s.is_cycled " +
                "FROM pg_class c " +
                "JOIN pg_namespace n ON c.relnamespace = n.oid " +
                "JOIN pg_sequences s ON n.nspname = s.schemaname AND c.relname = s.sequencename " +
                "WHERE n.nspname = ? " +
                "AND c.relkind = 'S' " +
                "AND c.relname = ANY (?)"; // 支持多个序列名称的查询

        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            // 设置模式名和序列名列表
            ps.setString(1, schema);
            Array sequenceNamesArray = connection.createArrayOf("VARCHAR", sequenceNames.toArray());
            ps.setArray(2, sequenceNamesArray);

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    String sequenceName = rs.getString("sequence_name");
                    long startValue = rs.getLong("start_value");
                    long incrementBy = rs.getLong("increment_by");
                    long minValue = rs.getLong("min_value");
                    long maxValue = rs.getLong("max_value");
                    int cacheSize = rs.getInt("cache_size");
                    boolean isCycled = rs.getBoolean("is_cycled");

                    // 拼接每个序列的 DDL 语句
                    StringBuilder ddl = new StringBuilder("CREATE SEQUENCE ")
                            .append(schema).append(".").append(sequenceName)
                            .append(" START ").append(startValue)
                            .append(" INCREMENT ").append(incrementBy)
                            .append(" MINVALUE ").append(minValue)
                            .append(" MAXVALUE ").append(maxValue)
                            .append(" CACHE ").append(cacheSize)
                            .append(isCycled ? " CYCLE" : " NO CYCLE");

                    // 将拼接好的 DDL 语句放入 Map 中
                    sequenceDDLMap.put(sequenceName, ddl.toString());
                }
            }
        }

        return sequenceDDLMap;
    }
}
